package com.vapps.planificaciojubilacio;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;


public class Dades extends Activity implements OnEditorActionListener {
	private EditText et_data_naixem;
	private EditText et_anys_cotit;
	private EditText et_salari_brut;
	private EditText et_ipc;
	private EditText et_inc_salari;
	
	private Button b_data_naixem;
	private Button b_anys_cotit;
	private Button b_salari_brut;
	private Button b_inc_ipc;
	private Button b_dec_ipc;
	private Button b_ipc;
	private Button b_inc_salari;
	private Button b_dec_salari;
	private Button b_salari;
	private Button b_validar;

	private double ipc;
	private double incremSalari;
	
	// Number Format
	private NumberFormat numF;
	// Resources instance for application's package
	private Resources res;
	// Dynamic time sufix fields
	private String dynamicTimeSufix;
	// tmpFieldValue for saving field value until user exits from it
	private String tmpFieldValue;

	private ArrayAdapter<CharSequence> adapter;

	// Constants
	static final double IPC_INITIAL = 0.015;
	static final double INCREMENT_SALARI_INICIAL = 0.015;

	// LayoutParams
	private TableRow.LayoutParams params;
	private TableRow.LayoutParams paramsApr;

	float scaleFactor;

	public static final String PREFS_NAME = "MyPrefsFile";

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dades);

		initialize();

		redrawDependingMainHelp( ScrollableTabActivity.mainHelpEnabled );
	};

	public void initialize() {
		// Attach UI widgets
		et_data_naixem = (EditText) findViewById(R.id.et_data_naixem);
		et_anys_cotit = (EditText) findViewById(R.id.et_anys_cotit);
		et_salari_brut = (EditText) findViewById(R.id.et_salari_brut);
		et_ipc = (EditText) findViewById(R.id.et_ipc);
		et_inc_salari = (EditText) findViewById(R.id.et_salari);
		b_data_naixem = (Button) findViewById(R.id.b_data_naixem);
		b_anys_cotit = (Button) findViewById(R.id.b_anys_cotit);
		b_salari_brut = (Button) findViewById(R.id.b_salari_brut);
		b_inc_ipc = (Button) findViewById(R.id.b_inc_ipc);
		b_dec_ipc = (Button) findViewById(R.id.b_dec_ipc);
		b_ipc = (Button) findViewById(R.id.b_ipc);
		b_inc_salari = (Button) findViewById(R.id.b_inc_salari);
		b_dec_salari = (Button) findViewById(R.id.b_dec_salari);
		b_salari = (Button) findViewById(R.id.b_salari);
		b_validar = (Button) findViewById(R.id.b_validar);

		// Formating percentage number
		numF = NumberFormat.getPercentInstance();
		if (numF instanceof DecimalFormat) {
			((DecimalFormat) numF).setDecimalSeparatorAlwaysShown(true);
			((DecimalFormat) numF).setMaximumFractionDigits(3);
			((DecimalFormat) numF).setMinimumFractionDigits(3);
			((DecimalFormat) numF).setMinimumIntegerDigits(1);
		}

		// Gets resources instance for application's package
		res = getResources();

		// Widgets initializations
		et_data_naixem.setText("01/01/1971");
		et_anys_cotit.setText("20");
		et_salari_brut.setText(NumberFormat.getCurrencyInstance().format(45000));
		et_ipc.setText(numF.format(IPC_INITIAL));
		et_inc_salari.setText(numF.format(INCREMENT_SALARI_INICIAL));
		dynamicTimeSufix = res.getString(R.string.anys_sufix);

		// Variables initializations
		ipc				= IPC_INITIAL;
		incremSalari	= INCREMENT_SALARI_INICIAL;

		// Params initialization
		paramsApr = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		params = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		// Screen scale factor
		scaleFactor = res.getDisplayMetrics().density;

		// Listeners declaration
		////////////////////////////////////////////////////////////////////////////////

		et_data_naixem.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (v.isFocusableInTouchMode()) {
					et_data_naixem.setText("");
				}
				return false;
			}
		});
		et_data_naixem.setOnEditorActionListener(this);

		et_anys_cotit.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (v.isFocusableInTouchMode()) {
					et_anys_cotit.setText("");
				}
				return false;
			}
		});
		et_anys_cotit.setOnEditorActionListener(this);
		
		et_salari_brut.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (v.isFocusableInTouchMode()) {
					et_salari_brut.setText("");
				}
				return false;
			}
		});
		et_salari_brut.setOnEditorActionListener(this);
		
		et_ipc.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (v.isFocusableInTouchMode()) {
					et_ipc.setText("");
				}
				return false;
			}
		});
		et_ipc.setOnEditorActionListener(this);
		
		b_inc_ipc.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ipc = ipc + 0.0025;
				et_ipc.setText(numF.format(ipc));
			}
		});
		b_dec_ipc.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ipc = ipc - 0.0025;
				et_ipc.setText(numF.format(ipc));
			}
		});
		
		et_inc_salari.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (v.isFocusableInTouchMode()) {
					ipc = ipc + (0.25);
					et_ipc.setText(numF.format(ipc));
				}
				return false;
			}
		});
		et_inc_salari.setOnEditorActionListener(this);
		
		b_inc_salari.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				incremSalari = incremSalari + 0.0025;
				et_inc_salari.setText(numF.format(incremSalari));
			}
		});
		b_dec_salari.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				incremSalari = incremSalari - 0.0025;
				et_inc_salari.setText(numF.format(incremSalari));
			}
		});
		
		b_validar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
			}
		});
	
		
		// Information context buttons
		// //////////////////////////////////////////////////////////////////////////////
		if (b_anys_cotit != null) {
			b_data_naixem.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					showInfDialog(R.string.data_naixement_inf,
							R.string.data_naixement_tit);
				}
			});
			b_anys_cotit.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					showInfDialog(R.string.anys_cotit_inf, R.string.anys_cotit_tit);
				}
			});
			b_salari_brut.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					showInfDialog(R.string.salari_brut_inf,
							R.string.salari_brut_tit);
				}
			});
			b_ipc.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					showInfDialog(R.string.ipc_inf, R.string.ipc_tit);
				}
			});
			b_salari.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					showInfDialog(R.string.salari_inf, R.string.salari_tit);
				}
			});
		}
	}

	// OnEditorActionListener implementation
	public boolean onEditorAction(TextView textView, int actionId,
			KeyEvent event) {
		if (event != null) {
			// If the user enters a value and press ENTER it's stored, otherwise sets the current value
			if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && textView.getText().length() > 0) {
				// Main process
				BigDecimal currentValue;
				switch (textView.getId()) {
				case R.id.et_salari_brut:
					currentValue = new BigDecimal(et_salari_brut.getText()
							.toString().replace(',', '.'));
					et_salari_brut.setText(NumberFormat.getCurrencyInstance()
							.format(currentValue));
					break;
				case R.id.et_ipc:
					currentValue = new BigDecimal(et_ipc.getText().toString()
							.replace(',', '.'));
					et_ipc.setText(et_ipc.getText().toString() + "%");
					ipc = currentValue.doubleValue();
					break;
				case R.id.et_salari:
					currentValue = new BigDecimal(et_inc_salari.getText().toString()
							.replace(',', '.'));
					et_inc_salari.setText(et_inc_salari.getText().toString() + "%");
					incremSalari = currentValue.doubleValue();
					break;
				}

			// Hides keyboard
			InputMethodManager imm = (InputMethodManager) getBaseContext()
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return false;
	}

	private void showInfDialog(int msg, int title) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg).setPositiveButton(R.string.accept,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
					}
				});
		// Title for AlertDialog
		builder.setTitle(title);
		// Icon for AlertDialog
		builder.setIcon(R.drawable.ic_dialog_info_in);
		builder.show();
	}

	private void redrawDependingMainHelp( boolean bMainHelpEnabled ){
		int dp;
	
		// Main help enabled
		if (bMainHelpEnabled) {
			// Setting layout_marginLeft
			dp = 20;
			params.setMargins((int) (dp * scaleFactor + 0.5f), 0, 0, 0);
			et_data_naixem.setLayoutParams(params);
			et_anys_cotit.setLayoutParams(params);
			et_salari_brut.setLayoutParams(params);
	
			// Setting field width
			dp = 100;
			//etApr.setWidth((int) (dp * scaleFactor + 0.5f));
			//etEar.setWidth((int) (dp * scaleFactor + 0.5f));
	
			// Setting buttons visibility
			b_data_naixem.setVisibility(View.VISIBLE);
			b_anys_cotit.setVisibility(View.VISIBLE);
			b_salari_brut.setVisibility(View.VISIBLE);
			b_ipc.setVisibility(View.VISIBLE);
			b_salari.setVisibility(View.VISIBLE);

		} else {
			// Default parameters
			// Setting layout_marginLeft
			dp = 50;
			params.setMargins((int) (dp * scaleFactor + 0.5f), 0, 0, 0);
			et_data_naixem.setLayoutParams(params);
			et_anys_cotit.setLayoutParams(params);
			et_salari_brut.setLayoutParams(params);
	
			// Setting field width
			dp = 130;
			//etApr.setWidth((int) (dp * scaleFactor + 0.5f));
			//etEar.setWidth((int) (dp * scaleFactor + 0.5f));
	
			// Setting buttons visibility
			b_data_naixem.setVisibility(View.GONE);
			b_anys_cotit.setVisibility(View.GONE);
			b_salari_brut.setVisibility(View.GONE);
			b_ipc.setVisibility(View.GONE);
			b_salari.setVisibility(View.GONE);
		}
	}

	// Called when activity starts (before intentCalc.putExtra() is called)
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		if (intent.getExtras() != null) {
			redrawDependingMainHelp( intent.getExtras().getBoolean("MainHelpEnabled") );
		}
	}
}